﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
using VAdvantage.Model;
using System.Data;
using VAdvantage.DataBase;
using System.Threading;
using VAdvantage.Classes;

namespace VAdvantage.Apps
{
    public partial class FramePane : CFrame
    {
        KeyNamePair[] colors = null;

        public FramePane()
            : base(Msg.GetMsg("AddFrame"))
        {

        }

        void SetBusy(bool b)
        {
            SetBusy(false, "");
        }

        void SetBusy(bool b, String t)
        {
            if (b)
            {
                busyWindow.Visibility = System.Windows.Visibility.Visible;
                txtBusy.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                busyWindow.Visibility = System.Windows.Visibility.Collapsed;
            }
            txtBusy.Text = t;

        }

        public FramePane(int rcviewid)
            : base(Msg.GetMsg("AddPanel"))
        {
            //InitializeComponent();

            //SetBusy(true, Msg.GetMsg("Loading"));

            //this.Visibility = System.Windows.Visibility.Visible;
            //LoadDBText();

            //LoadTabs();

        }

        List<KeyNamePair> _tabList = new List<Model.KeyNamePair>();
        void LoadTabs(List<KeyNamePair> tabList)
        {
            if (tabList.Count <= 0)
            {
                LoadFromDatabase();

            }
            else
            {
                int index = 0;
                for (int i = 0; i <= tabList.Count - 1; i++)
                {
                    cmbTab.Items.Add(tabList[i]);
                    if (rolecenter != null)
                    {

                        if (tabList[i].GetKey() == rolecenter.RC_Tab_ID)
                            index = i;
                    }
                }
                cmbTab.SelectedIndex = index;
            }
        }

        private void LoadFromDatabase()
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                string sql = @"
                    SELECT 
                      rct.Name, rct.RC_RoleCenterTab_ID
                    FROM rc_rolecentermanager rcm
                    INNER JOIN rc_rolecentertab rct
                    ON rcm.rc_rolecentermanager_id = rct.rc_rolecentermanager_id 
                    where rcm.IsActive = 'Y' and rcm.ad_role_id = " + Envs.GetCtx().GetAD_Role_ID();

                _tabList.Clear();
                IDataReader dr = DB.ExecuteReader(sql);
                while (dr.Read())
                {
                    KeyNamePair key = new KeyNamePair(int.Parse(dr["RC_RoleCenterTab_ID"].ToString()), dr[0].ToString());
                    Dispatcher.BeginInvoke(() => cmbTab.Items.Add(key));
                }
                dr.Close();
            });
        }

        ViennaRoleCenter rolecenter = null;

        public FramePane(ViennaRoleCenter _rolecenter)
            : base(Msg.GetMsg("AddPanel"))
        {
            rolecenter = _rolecenter;
            InitializeComponent();

            SetBusy(true, Msg.GetMsg("Loading"));

            this.Visibility = System.Windows.Visibility.Visible;
            LoadDBText();
            if (rolecenter != null)
            {

                LoadTabs(rolecenter.ListTab);
            }
            else
                LoadTabs(new List<KeyNamePair>());

            //SetBusy(false);
        }

        /// <summary>
        /// Loads Label Texts from Database
        /// </summary>
        void LoadDBText()
        {
            lblName.Content = Msg.GetMsg("Title");
            lblFrames.Content = Msg.GetMsg("View");
            lblMinValue.Content = Msg.GetMsg("MinValue");
            lblMaxValue.Content = Msg.GetMsg("MaxValue");
            lblBGColor.Content = Msg.GetMsg("BGColor");
            lblHeaderBGColor.Content = Msg.GetMsg("HeaderBGColor");
            //lblHeaderFontColor.Content = Msg.GetMsg("HeaderFontColor");
            //lblFontColor.Content = Msg.GetMsg("FontColor");
            lblSeq.Content = Msg.GetMsg("SeqNo");

            lblColspan.Content = Msg.GetMsg("Colspan");
            lblRowspan.Content = Msg.GetMsg("Rowspan");
            lblTabs.Content = Msg.GetMsg("Tab");
            LoadFramesInCombo();

            if (rolecenter != null)
            {
                if (rolecenter.EditMode)
                {
                    txtSeq.Text = rolecenter.SeqNo.ToString();
                    txtColspan.Text = rolecenter.Colspan.ToString();
                    txtRowspan.Text = rolecenter.Rowspan.ToString();
                    txtName.Text = rolecenter.PanelName;
                    txtMinValue.Text = rolecenter.MinValue.ToString();
                    txtMaxValue.Text = rolecenter.MaxValue.ToString();
                }
            }
        }

        void LoadFramesInCombo()
        {
            SetBusy(true, Msg.GetMsg("Loading"));
            int index = -1;
            int bgindex = -1;
            int hdrindex = -1;
            int hdrfntindex = -1;
            int fntindex = -1;

            ThreadPool.QueueUserWorkItem(delegate
            {

                int clientID = Envs.GetCtx().GetAD_Client_ID();
                int orgID = Envs.GetCtx().GetAD_Org_ID();
                //string sql = @"Select RC_View.RC_View_ID, RC_View.Name from RC_View RC_View WHERE IsActive = 'Y' AND (" + Envs.GetCtx().GetAD_Role_ID() + " IN (select AD_Role_ID from RC_ViewAccess where RC_View.rc_view_id = rc_view_id )  OR " + Envs.GetCtx().GetAD_User_ID() + " IN ( SELECT AD_User_ID from RC_ViewAccess where RC_View.rc_view_id = rc_view_id )) ";
                string sql = @"SELECT 
                                distinct 
                                    rcview.RC_View_ID, 
                                    rcview.Name 
                                FROM RC_View rcview 
                                INNER JOIN RC_ViewAccess acc ON rcview.RC_View_ID = acc.RC_View_ID 
                                WHERE rcview.IsActive = 'Y' 
                                AND ((acc.AD_User_ID = " + Envs.GetCtx().GetAD_User_ID() + @")
                                OR (acc.AD_Role_ID = " + Envs.GetCtx().GetAD_Role_ID() + ")) ";

                string s = MRole.GetDefault().AddAccessSQL(sql, "RC_View", true, false);

                KeyNamePair[] views = null;
                IDataReader dr = DB.ExecuteReader(s);
                List<KeyNamePair> list = new List<KeyNamePair>();
                while (dr.Read())
                {
                    KeyNamePair key = new KeyNamePair(int.Parse(dr["RC_View_ID"].ToString()), dr["Name"].ToString());
                    list.Add(key);
                }
                dr.Close();

                if (list.Count > 0)
                {
                    views = list.ToArray();


                    Dispatcher.BeginInvoke(delegate
                    {

                        for (int i = 0; i <= views.Count() - 1; i++)
                        {
                            cmbFrames.Items.Add(views[i] as KeyNamePair);

                            if (rolecenter != null)
                            {

                                if (views[i].GetKey() == rolecenter.RC_View_ID)
                                    index = i;
                            }
                        }

                    });
                }

                //sql = "Select AD_PrintColor_ID, Name from AD_PrintColor Where IsActive = 'Y'";
                //dr = DB.ExecuteReader(sql, null);
                List<KeyNamePair> lColors = new List<KeyNamePair>();
                //int counter = 0;
                //while (dr.Read())
                //{

                //    lColors.Add(new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString()));
                //    KeyNamePair keys = new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString());

                //    bool pass = false;

                //    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                //    {

                //        cmbBGColor.Items.Add(keys);

                //        if (rolecenter.EditMode)
                //        {
                //            if (rolecenter.BGColor_ID.ToString().Equals(keys.GetID()))
                //            {
                //                bgindex = counter;
                //            }
                //        }

                //        cmbHeaderBGColor.Items.Add(keys);
                //        if (rolecenter.HeaderBGColor_ID.ToString().Equals(keys.GetID()))
                //        {
                //            hdrindex = counter;
                //        }

                //        pass = true;

                //    });

                //    while (!pass)
                //        Thread.Sleep(0);

                //    pass = false;


                //    //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                //    //{
                //    //    cmbHeaderFontColor.Items.Add(keys);
                //    //    if (rolecenter.HeaderFontColor_ID.Equals(keys.GetID()))
                //    //    {
                //    //        hdrfntindex = counter;
                //    //    }

                //    //});


                //    //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                //    //{
                //    //    cmbFontColor.Items.Add(keys);
                //    //    if (rolecenter.FontColor_ID.Equals(keys.GetID()))
                //    //    {
                //    //        fntindex = counter;
                //    //    }

                //    //});

                //    counter++;
                //}
                //dr.Close();

                if (list.Count > 0)
                    colors = lColors.ToArray();



                if (rolecenter != null)
                {

                    if (rolecenter.EditMode)
                    {
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbFrames.SelectedIndex = index);
                        //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbBGColor.SelectedIndex = bgindex);
                        //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbHeaderBGColor.SelectedIndex = hdrindex);
                        //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbHeaderFontColor.SelectedIndex = hdrfntindex);
                        //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbFontColor.SelectedIndex = fntindex);
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbFrames.SetReadOnly(true));
                    }
                }

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => SetBusy(false));
            });
        }

        private void cmbFrames_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadData();
        }

        void LoadData()
        {
            if (!rolecenter.EditMode)
            {
                SetBusy(true, "Please Wait");
                KeyNamePair selected = cmbFrames.SelectedItem as KeyNamePair;
                if (selected == null)
                    return;

                cmbBGColor.SelectedIndex = -1;
                //cmbHeaderFontColor.SelectedIndex = -1;
                cmbHeaderBGColor.SelectedIndex = -1;
                //cmbFontColor.SelectedIndex = -1;

                ThreadPool.QueueUserWorkItem(delegate
                {
                    //check save or update
                    //string sql = "select RC_ViewPane_ID from RC_ViewPane where IsActive = 'Y' AND RC_View_ID = " + selected.GetKey();
                    //Object oid = DB.ExecuteScalar(sql);
                    //int id = 0;
                    //if (oid != null)
                    //    id = int.Parse(oid.ToString());

                    //if (id == 0)
                    {
                        X_RC_View view = new X_RC_View(Envs.GetCtx(), selected.GetKey(), null);

                        Dispatcher.BeginInvoke(delegate
                        {
                            txtName.Text = view.GetTitle();
                            txtMinValue.Text = view.GetMinValue().ToString();
                            txtMaxValue.Text = view.GetMaxValue().ToString();
                            //int bgcolorid = view.GetBG_Color_ID();
                            //int headerbgid = view.GetHeaderBG_Color_ID();
                            //int headercolorid = view.GetHeaderFont_Color_ID();
                            //int fontcolorid = view.GetFont_Color_ID();

                            //if (colors != null)
                            //{
                            //    for (int c = 0; c <= colors.Length - 1; c++)
                            //    {
                            //        if (bgcolorid == colors[c].GetKey())
                            //            cmbBGColor.SelectedIndex = c;
//
  //                          //        if (headerbgid == colors[c].GetKey())
                                //        cmbHeaderBGColor.SelectedIndex = c;
                            //
                                    //if (headercolorid == colors[c].GetKey())
                                    //    cmbHeaderFontColor.SelectedIndex = c;

                                    //if (fontcolorid == colors[c].GetKey())
                                    //    cmbFontColor.SelectedIndex = c;
                                //}
                            //}
                            SetBusy(false);
                        });
                    }
                    //else
                    //{
                    //    X_RC_ViewPane view = new X_RC_ViewPane(Envs.GetCtx(), id, null);

                    //    Dispatcher.BeginInvoke(delegate
                    //    {
                    //        txtName.Text = view.GetName();
                    //        txtMinValue.Text = view.GetMinValue().ToString();
                    //        txtMaxValue.Text = view.GetMaxValue().ToString();
                    //        //txtColspan.Text = view.GetColspan().ToString();
                    //        //txtRowspan.Text = view.GetRowspan().ToString();
                    //        //txtSeq.Text = view.GetSeqNo().ToString();

                    //        //int bgcolorid = view.GetBG_Color_ID();
                    //        //int headerbgid = view.GetHeaderBG_Color_ID();
                    //        //int headercolorid = view.GetHeaderFont_Color_ID();
                    //        //int fontcolorid = view.GetFont_Color_ID();

                    //        //if (colors != null)
                    //        //{
                    //        //    for (int c = 0; c <= colors.Length - 1; c++)
                    //        //    {
                    //        //        if (bgcolorid == colors[c].GetKey())
                    //        //            cmbBGColor.SelectedIndex = c;

                    //        //        if (headerbgid == colors[c].GetKey())
                    //        //            cmbHeaderBGColor.SelectedIndex = c;

                    //        //        //if (headercolorid == colors[c].GetKey())
                    //        //        //    cmbHeaderFontColor.SelectedIndex = c;

                    //        //        //if (fontcolorid == colors[c].GetKey())
                    //        //        //    cmbFontColor.SelectedIndex = c;
                    //        //    }
                    //        //}
                    //        SetBusy(false);
                    //    });
                    //}

                });
            }
        }

        private void cmbBGColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void bOK_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

        }

        #region FormPanel Members

        private FormFrame _frame;

        public void Init(int windowNo, FormFrame frame)
        {
            InitializeComponent();

            this.Visibility = System.Windows.Visibility.Visible;
            _frame = frame;
            _frame.ContentGrid.Children.Add(this);
            LoadDBText();
        }

        #endregion

        #region FormPanel Members


        public void Dispose()
        {

        }

        #endregion

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            KeyNamePair tabSelected = (KeyNamePair)cmbTab.SelectedItem;
            if (cmbFrames.SelectedIndex < 0)
            {
               // ShowMessage.Error("SelectFrame", false);
                ShowMessage.Error("SelectView", false);
                return;
            }
            else if (string.IsNullOrEmpty(txtName.Text))
            {
                ShowMessage.Error("EnterName", false);
                return;
            }
            else if (string.IsNullOrEmpty(txtMinValue.Text))
            {
                ShowMessage.Error("EnterMinValue", false);
                return;
            }
            else if (string.IsNullOrEmpty(txtMaxValue.Text))
            {
                ShowMessage.Error("EnterMaxValue", false);
                return;
            }
            else if (string.IsNullOrEmpty(txtColspan.Text))
            {
                ShowMessage.Error("EnterColspan", false);
                return;
            }
            else if (string.IsNullOrEmpty(txtRowspan.Text))
            {
                ShowMessage.Error("EnterRowspan", false);
                return;
            }

            SetBusy(true, "Saving");
            int rcviewid = (cmbFrames.SelectedItem as KeyNamePair).GetKey();

            try
            {
                string name = txtName.Text;
                int colspan = int.Parse(txtColspan.Text);
                int rowspan = int.Parse(txtRowspan.Text);
                int seqno = int.Parse(txtSeq.Text);
                int minvalue = int.Parse(txtMinValue.Text);
                int maxvalue = int.Parse(txtMaxValue.Text);
                KeyNamePair frameSelected = (KeyNamePair)cmbTab.SelectedItem;

                if (colspan > 3)
                    colspan = 3;

                if (colspan <= 0)
                    colspan = 1;

                if (rowspan > 2)
                    rowspan = 2;

                if (rowspan <= 0)
                    rowspan = 1;

                //int bgcolorid = (cmbBGColor.SelectedItem as KeyNamePair).GetKey();
                //int headercolorid = (cmbHeaderBGColor.SelectedItem as KeyNamePair).GetKey();
                //int headerfontcolorid = (cmbHeaderFontColor.SelectedItem as KeyNamePair).GetKey();
                //int fontcolorid = (cmbFontColor.SelectedItem as KeyNamePair).GetKey();
                bool isSaved = false;

                ThreadPool.QueueUserWorkItem(delegate
                {
                    int rcpanelid = 0;
                    int id = 0;

                    if (rolecenter != null)
                    {

                        if (rolecenter.EditMode)
                        {
                            rcpanelid = rolecenter.TabPanel_ID;
                            id = rolecenter.FramePane_ID;
                        }
                    }

                    X_RC_ViewPane pane = new X_RC_ViewPane(Envs.GetCtx(), id, null);
                    pane.SetRC_View_ID(rcviewid);
                    pane.SetName(name);
                    pane.SetColspan(colspan);
                    pane.SetRowspan(rowspan);
                    pane.SetSeqNo(seqno);
                    //pane.SetBG_Color_ID(bgcolorid);
                    //pane.SetHeaderBG_Color_ID(headercolorid);
                    //pane.SetHeaderFont_Color_ID(headerfontcolorid);
                    //pane.SetFont_Color_ID(fontcolorid);
                    pane.SetMinValue(minvalue);
                    pane.SetMaxValue(maxvalue);

                    if (pane.Save())
                    {
                        X_RC_TabPanels tabPanel = new X_RC_TabPanels(Envs.GetCtx(), rcpanelid, null);
                        tabPanel.SetRecord_ID(pane.Get_ID());
                        tabPanel.SetRoleCenterPanels("1");
                        tabPanel.SetColspan(colspan);
                        tabPanel.SetRowspan(rowspan);
                        tabPanel.SetSeqNo(seqno);
                        tabPanel.SetRC_RoleCenterTab_ID(frameSelected.GetKey());

                        isSaved = tabPanel.Save();
                        if (isSaved)
                        {
                            Dispatcher.BeginInvoke(delegate
                            {
                                ShowMessage.Info(Msg.GetMsg("RecordSaved"), false, "", "");
                                if (!rolecenter.EditMode)
                                {
                                    cmbFrames.SelectedIndex = -1;
                                    cmbTab.SelectedIndex = -1;
                                    txtName.Text = "";
                                    txtMaxValue.Text = "";
                                    txtMaxValue.Text = "";
                                    cmbBGColor.SelectedIndex = -1;
                                    cmbHeaderBGColor.SelectedIndex = -1;
                                    txtColspan.Text = "";
                                    txtRowspan.Text = "";
                                    txtSeq.Text = "";
                                }
                                SetBusy(false);
                            });
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(delegate
                            {
                                ShowMessage.Info(Msg.GetMsg("RecordNotSaved"), false, "", "");
                                SetBusy(false);
                            });

                        }
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(delegate
                        {
                            ShowMessage.Info(Msg.GetMsg("RecordNotSaved"), false, "", "");
                            SetBusy(false);
                        });
                    }
                });
            }
            catch
            {
                ShowMessage.Info(Msg.GetMsg("InvalidData"), false, "", "");
                SetBusy(false);
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
